package top.rainf.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 星环
 * @date 2023/5/10 9:32:18
 * @description 因为愚蠢的Springboot不能修改Set-Cookie的值，只好在每次设置cookie后都把cookie重写一遍 加上SameSite=None
 */
@Slf4j
@Repository("true")
@Scope("prototype")
public class CookieSetter {
    private boolean headerChanged = false;
    StringBuilder stringBuilder = new StringBuilder();
    private final HttpServletRequest request;
    private final HttpServletResponse response;

    public HttpServletRequest getRequest() {
        return request;
    }

    public HttpServletResponse getResponse() {
        return response;
    }

    @Autowired
    public CookieSetter(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("gen");
        System.out.println(request);
        this.request = request;
        this.response = response;
    }

    public CookieSetter setSessionAttr(String key, String value){

        request.getSession().setAttribute(key,value);
        if(headerChanged){
            return this;
        }
        headerChanged = true;
        String header = response.getHeader("Set-Cookie");
        if(!StringUtil.isNullOrEmpty(header)){
            log.info("设置session，愚蠢的Samesite ：{}",header);
            stringBuilder.append(header).append("; Secure;").append(" SameSite=None");
            response.setHeader("Set-Cookie",stringBuilder.toString());
        }
        return this;
    }
    //public void setCookie(String key, String value, HttpServletRequest request, HttpServletResponse response)
}
